<?php
/**
 * Created by PhpStorm.
 * Author: sitenv@aliyun.com
 * CreateTime: 2021/07/09 14:30
 * Blog：www.myblogs.xyz
 */

namespace app\common\model;


class MemberToken extends Common
{
    protected $name = 'member_token';
    protected $pk = 'token';

    public function getToken($account, $member_id, $is_update = false, $type = 1)
    {
        $create_time = NEW_TIME;
        $expire_time = $create_time + (3600 * 24 * 10);
        $token = $this->where(['member_id'=>$member_id,'type'=>$type])->value('token');
        if (!$is_update && !empty($token)){
            $this->where(['member_id'=>$member_id,'type'=>$type])->update(['expire_time'=>$expire_time]);
        }else{
            $save_data = [
                'type'=>$type,
                'account'=>$account,
                'member_id'=>$member_id,
                'create_time'=>$create_time,
                'expire_time'=>$expire_time,
            ];
            $token = md5(sha1(http_build_query($save_data)));
            $save_data['token'] = $token;
            if (!empty($token)){
                $this->where(['member_id'=>$member_id,'type'=>$type])->delete();
            }
            $this->insert($save_data);
        }
        return $token;
    }

    public function tokenAuth($token)
    {
        $token_data = $this->getFind(['token'=>$token]);
        if (!empty($token_data)){
            if ($token_data['expire_time'] > NEW_TIME){
                $this->getToken($token_data['account'], $token_data['member_id'], false, $token_data['type']);
                return $token_data;
            }
        }
        return false;
    }

}